package com.yksj.healthtalk.ui.doctorstation.service;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 分组编辑
 * @author zhao
 *
 */
public class DoctorServiceGroupEditorActivity extends BaseFragmentActivity implements OnClickListener, OnItemSelectedListener{
	
	ListView mListView;
	DataListAdapter mAdapter;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.doctor_service_group_editor_layout);
		initUI();
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.group_add_btn://添加组
		case R.id.group_add_txtv:
			JSONObject jsonObject2;
			if(mAdapter.mArray.size()==0){
//				 jsonObject2 = mAdapter.mArray.getJSONObject(0);
				 mAdapter.addGroup();
			}else{
				 jsonObject2 = mAdapter.mArray.getJSONObject(mAdapter.mArray.size()-1);
					if(jsonObject2.getString("PATIENT_GROUP").trim().length() > 0){
						mAdapter.addGroup();
						}else{
							ToastUtil.showShort("请输入分类名称");
						}
			}

			break;
		case R.id.title_right2:
			JSONArray array = new JSONArray();
			for (int i = 0; i < mAdapter.mArray.size();i++) {
				JSONObject jsonObject = mAdapter.mArray.getJSONObject(i);
				if(jsonObject.getString("PATIENT_GROUP").trim().length() > 0){//"0".equals(jsonObject.getString("PATIENT_GROUP_ID")) && 
						array.add(jsonObject);
				}
			}
			onUpdateGroups(array);
			break;
		}
	}
	
	private void initUI(){
		initTitle();
		
		titleTextV.setText("分组管理");
		
		setBackBtn("返回",this);
		setRightBtnYellowBg("确定",this);
		mListView = (ListView)findViewById(R.id.listView1);
		
		View footV = getLayoutInflater().inflate(R.layout.add_group_item_layout, null);
		footV.findViewById(R.id.group_add_btn).setOnClickListener(this);
		footV.findViewById(R.id.group_add_txtv).setOnClickListener(this);
		mListView.addFooterView(footV,null,false);
		mListView.setAdapter(mAdapter = new DataListAdapter());
		mListView.requestFocus();
		mListView.setOnItemSelectedListener(this);
		
		initData();
	}
	
	/**
	 * 初始化分组
	 */
	private void initData(){
		HttpRestClient.doHttpQueryGroups(SmartFoxClient.getLoginUserId(),new JsonsfHttpResponseHandler(this){
			@Override
			public void onSuccess(int statusCode,JSONArray response) {
				super.onSuccess(statusCode, response);
				mAdapter.onDataChange(response);
			}
		});
	}
	
	
	/**
	 * 更改,添加
	 */
	private void onUpdateGroups(JSONArray array){
		if(array.size() == 0) return;
		HttpRestClient.doHttpAddGroup(SmartFoxClient.getLoginUserId(), array.toJSONString(), new JsonsfHttpResponseHandler(this){
			@Override
			public void onSuccess(int statusCode,JSONObject response) {
				super.onSuccess(statusCode, response);
				if(!response.containsKey("error_code")){
					ToastUtil.showShort(response.getString("error_code"));
				}
			}
			@Override
			public void onSuccess(int statusCode, JSONArray response) {
				super.onSuccess(statusCode, response);
				mAdapter.holder.group_menber.setVisibility(View.VISIBLE);
				mAdapter.onDataChange(response);
				ToastUtil.showToastPanl("处理成功");
			}
		});
	}
	
	/**
	 * 删除分组 
	 * @param object
	 */
	private void onDeleteGroups(final JSONObject object){
		HttpRestClient.doHttpRemoveGroup(SmartFoxClient.getLoginUserId(),object.getString("PATIENT_GROUP_ID"),new JsonsfHttpResponseHandler(this){
			@Override
			public void onSuccess(int statusCode, JSONArray response) {
				super.onSuccess(statusCode, response);
				mAdapter.deleteGroup(object);
				ToastUtil.showToastPanl("删除成功");
			}
			@Override
			public void onSuccess(int statusCode,  JSONObject response) {
				if(!response.containsKey("error_code")){
					ToastUtil.showShort(response.getString("error_code"));
				}
			}
		});
	}
	
	class DataListAdapter extends BaseAdapter{
		JSONArray mArray = new JSONArray();
		ViewHolder holder;
		public void onDataChange(JSONArray array){
			this.mArray = array;
			notifyDataSetChanged();
		}
		
		/**
		 * 添加分组
		 */
		public void addGroup(){
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("PATIENT_GROUP_ID", "0");
			jsonObject.put("PATIENT_GROUP", "");
			mArray.add(jsonObject);
			notifyDataSetChanged();
		}
		
		public void deleteGroup(JSONObject jsonObject){
			mArray.remove(jsonObject);
			notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return mArray.size();
		}

		@Override
		public Object getItem(int position) {
			return mArray.getJSONObject(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			final JSONObject  jsonObject = (JSONObject)getItem(position);
			
			if(convertView == null){
				convertView = getLayoutInflater().inflate(R.layout.delete_group_item_layout, null);
				holder = new ViewHolder();
				holder.group_delet = convertView.findViewById(R.id.group_delet);
				holder.group_name  = (EditText)convertView.findViewById(R.id.group_name);
				holder.group_menber = convertView.findViewById(R.id.group_menber);
				convertView.setTag(holder);
			}else{
				holder = (ViewHolder)convertView.getTag();
			}
			//删除
			holder.group_delet.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					DoubleBtnFragmentDialog.showDefault(getSupportFragmentManager(), 
							 "您确定删除 "+jsonObject.getString("PATIENT_GROUP")+" 分组？",
							"放弃", 
							"确定",new OnDilaogClickListener() {
								@Override
								public void onDismiss(DialogFragment fragment) {
								}
								@Override
								public void onClick(DialogFragment fragment, View v) {
									String id = jsonObject.getString("PATIENT_GROUP_ID");
									if("0".equals(id)){
										deleteGroup(jsonObject);
									}else{
										onDeleteGroups(jsonObject);
									}
								}
							});
				}
			});
			holder.group_name.removeTextChangedListener(holder.textWatcher);
			holder.group_name.setText(jsonObject.getString("PATIENT_GROUP"));
			holder.group_name.addTextChangedListener(holder.textWatcher = new TextWatcher() {
				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
				}
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {
				}
				@Override
				public void afterTextChanged(Editable s) {
					jsonObject.put("PATIENT_GROUP",s.toString());
				}
			});
			
			//如果name 没有文字的话  就隐藏成员
			if(TextUtils.isEmpty(holder.group_name.getText().toString())){
				holder.group_menber.setVisibility(View.GONE);
			}else{
				holder.group_menber.setVisibility(View.VISIBLE);
			}
			
			//查看分组成员
			holder.group_menber.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if("0".equals(jsonObject.getString("PATIENT_GROUP_ID")))return;
					Intent intent = new Intent(DoctorServiceGroupEditorActivity.this,DoctorServiceGroupMangeActivity.class);
					intent.putExtra("json",jsonObject.toJSONString());
					startActivity(intent);
				}
			});
			if("0".equals(jsonObject.getString("PATIENT_GROUP_ID")))
			holder.group_menber.setVisibility(View.INVISIBLE);
			return convertView;
		}
	}
	
	private static class ViewHolder{
		EditText group_name;
		View group_menber;
		View group_delet;
		TextWatcher textWatcher;
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position,
			long id) {
		mListView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
		EditText mGroupName= (EditText) view.findViewById(R.id.group_name);
		mGroupName.requestFocus();
		
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {
		mListView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
	}
}
